package com.sjy.shopmall.service.impl;

import com.sjy.shopmall.dao.CartMapper;
import com.sjy.shopmall.pojo.Cart;
import com.sjy.shopmall.service.CartService;
import com.sjy.shopmall.vo.CartDTO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {
    @Resource
    CartMapper cartMapper;

    @Override
    public List<CartDTO> findUserCartsDetails(Long userid) {

        return cartMapper.selectCartDto(userid);
    }

    @Override
    public void updateCount(Long id, BigDecimal bigDecimal) {
        if (BigDecimal.ZERO.compareTo(bigDecimal) > 0) {
            cartMapper.deleteByPrimaryKey(id);
        } else {
            Cart cart = cartMapper.selectByPrimaryKey(id);
            cart.setGoodCount(bigDecimal);
            cartMapper.updateByPrimaryKey(cart);
        }
    }


    /**
     * 函数的定义 definition
     *
     * @param userid 用户的id
     * @param goodId 商品id
     */
    @Override
    public void addCart(Long userid, Long goodId) {
        Cart cart = new Cart();
        cart.setOwner(userid);
        cart.setGoodId(goodId);
        Cart old = cartMapper.selectOne(cart);
        if (old == null) {
            cart.setGoodCount(BigDecimal.ONE);
            cartMapper.insert(cart);
        } else {
            old.setGoodCount(old.getGoodCount().add(BigDecimal.ONE));
            cartMapper.updateByPrimaryKey(old);
        }

    }
}
